/**
 * @author btan
 * @email: btan@tma.com.vn - anbtan@gmail.com
 */
package com.vital.mshopping;

import java.util.ArrayList;

import com.vital.dao.Category;
import com.vital.service.DatabaseService;
import com.vital.service.LocationService;

import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class MainActivity extends Activity {
	//---Member variable---
	ListView lvCategory;
	MainAdapter adapterCategory;
	ArrayList<Category> categories;
	boolean isCreate = true;
	ArrayList<Category> addedCategories; 
	String prevActivity = "";
	
	int reqCodeAddCategory = 0;
	int reqCodeEditCategory = 1;
	int posSelectedItem = -1;
	Context mContext;
	Category updatedCategory;
	LocationService gps;
	Location gpsLocation;
	
	double GPSLat;
	double GPSLng;
    /**
     * onCreate function
     * The first method is called by application
     */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        isCreate = true;
        mContext = this.getApplicationContext();
        
        //---Get list view from layout---
        lvCategory = (ListView)findViewById(R.id.lvCategory);
        
        //---Create array to store categories---
        categories = new ArrayList<Category>();
        
        gps = new LocationService(MainActivity.this);
        if (gps != null) {
        	new LoadCategoryTask().execute();
		} else {
			showSettingAlert();
			
		}
        
    }

	public void showSettingAlert() {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
		alertDialog.setTitle("GPS Settings");
		alertDialog.setMessage("GPS is not enabled. Do you want to enable this");
		
		alertDialog.setPositiveButton("Setting", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
				startActivity(intent);
				finish();
			}
		});
		
		alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
				finish();
			}
		});
		AlertDialog dialog = alertDialog.create();
		dialog.show();
	}
	/**
	 * onCreateOptionMenu
	 * create layout for option menu and it will be called when user touches setting button on Android
	 */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    /**
	 * onOptionsItemSelected
	 * This method will be called when user selects a desired item in Option Menu 
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
			case R.id.home_menu_addCategory:
				// Start Add Category Activity
				Intent intent = new Intent(mContext, AddCategoryActivity.class);
				startActivityForResult(intent, reqCodeAddCategory);
				//startActivity(intent);
				return true;
				
//			case R.id.home_menu_settings:
//				Toast.makeText(getApplicationContext(), "Coming up...", Toast.LENGTH_SHORT).show();
//				return true;
//				
//			case R.id.home_menu_aboutApp:
//				Toast.makeText(getApplicationContext(), "Coming up...", Toast.LENGTH_SHORT).show();
//				return true;
				
			case R.id.location_menu_history:
				Intent his_intent = new Intent(getApplicationContext(), HistoryActivity.class);
				startActivity(his_intent);
				return true;
				
			case R.id.location_menu_bookmark:
				Intent book_intent = new Intent(getApplicationContext(), BookmarkActivity.class);
				startActivity(book_intent);
				return true;
				
			default:
				return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Load list category from database
	 */
	private void loadCategoryFromDB() {
		//---variable---
		int cateId = 0;
		String cateName = "";
		String cateIcon = "";
		int cateReadOnly = 0;
		
		//---create a database service---
		DatabaseService db = new DatabaseService(this);
		
		//---get all categories from database---
		db.open();
		Cursor c = db.getAllCategories();
		if (c.moveToFirst()) {
			do {
				//---get value---
				cateId = c.getInt(0);
				cateName = c.getString(1);
				cateIcon = c.getString(2);
				cateReadOnly = c.getInt(3);
				
				//---add it to category list
				Category category = new Category(cateId, cateName, cateIcon, cateReadOnly);
				categories.add(category);
			} while (c.moveToNext());
		}
		//---close Cursor and database service---
		c.close();
		db.close();
    }
    
	/**
	 * set adapter for list view category
	 */
	private void setAdapterForListCategory() {
		adapterCategory = new MainAdapter(getApplicationContext(), R.layout.item_category, categories);
		//---Add Event Item Click Listener for ListView---
    	lvCategory.setOnItemClickListener(itemClickListener);
    	lvCategory.setOnItemLongClickListener(itemLongClickListener);
    	lvCategory.setAdapter(adapterCategory);
	}
	
	/**
	 * Event click an item on list view
	 */
    private OnItemClickListener itemClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			Category category = categories.get(position);
			//---put category object to Location Activity---
			Intent intent = new Intent(getApplicationContext(), LocationActivity.class);
			Bundle b = new Bundle();
			b.putSerializable("category", category);
			b.putDouble("latitute", gps.getLat());
			b.putDouble("longtitute", gps.getLng());
			intent.putExtras(b);
			startActivity(intent);
		}
	};
	
	/**
	 * Event long click an item on list view
	 */
	private OnItemLongClickListener itemLongClickListener = new OnItemLongClickListener() {
		public boolean onItemLongClick(AdapterView<?> parent, View view,
				int position, long id) {
			// TODO Auto-generated method stub
			Category category = categories.get(position); 
			int isReadOnly = category.getCateReadOnly();
			if (isReadOnly == 0) {
				//---Show Dialog with some options---
				showOptionMenu(position);
			}
			return false;
		}
	};
	
	/**
	 * show option menu with two options
	 * 1. Edit category
	 * 2. Delete category
	 */
	private void showOptionMenu(int position) {
		posSelectedItem = position;
		AlertDialog.Builder builder = new Builder(MainActivity.this);
		builder.setTitle(R.string.home_dialog_menu_title);
		
		builder.setItems(R.array.home_dialog_menu_array_choose, new OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (which) {
					case 0:
						// Edit Category
						editCategory(posSelectedItem);
						break;
					case 1:
						// Delete Category
						deleteCategory(posSelectedItem);
						break;
				}
			}
		});
		
		AlertDialog dialog = builder.create();
		dialog.show();
	};
	
	/**
	 * Edit a category
	 */
	private void editCategory(int position) {
		Intent intent = new Intent(getApplicationContext(), AddCategoryActivity.class);
		Category category = categories.get(position);
		intent.putExtra("editCategoryObject", category);
		startActivityForResult(intent, reqCodeEditCategory);
	};
	
	/**
	 * Delete a category
	 */
	private void deleteCategory(int position) {
		Category category = categories.get(position);
		long cateId = category.getCateId();
		DatabaseService db = new DatabaseService(getApplicationContext());
		db.open();
		if (db.deleteCategory(cateId)) {
			categories.remove(position);
			adapterCategory.notifyDataSetChanged();
		}
		db.close();
	}

	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (isCreate) {
			isCreate = false;
		} else {
			if (prevActivity == "AddActivity") {
				for (int i = 0; i < addedCategories.size(); i++) {
					Category savedCate = addedCategories.get(i);
					int cateId = savedCate.getCateId();
					String cateName = savedCate.getCateName();
					String cateIcon = savedCate.getCateIcon();
					int cateReadOnly = savedCate.getCateReadOnly();
					
					Category item = new Category(cateId, cateName, cateIcon, cateReadOnly);
					categories.add(item);
				}
				adapterCategory.notifyDataSetChanged();
				//---Reset value---
				addedCategories = new ArrayList<Category>();
				prevActivity = "";
			} else if (prevActivity == "UpdatedActivity"){
				for (int i = 0; i < categories.size(); i++) {
					Category category = categories.get(i);
					if (updatedCategory.getCateId() == category.getCateId()) {
						category.setCateName(updatedCategory.getCateName());
						category.setCateIcon(updatedCategory.getCateIcon());
					}
				}
				prevActivity = "";
				adapterCategory.notifyDataSetChanged();
			}
		}
		
	};
	
	
	/**
	 * The returned Data from Image View Activity
	 */
	@SuppressWarnings("unchecked")
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == reqCodeAddCategory) {
			if (resultCode == RESULT_OK) {
				prevActivity = "AddActivity";
				addedCategories	= (ArrayList<Category>) data.getExtras().getSerializable("list_added_categories");
				Log.d("TAG", addedCategories.size()+"");
			}
		} else if (requestCode == reqCodeEditCategory) {
			if (resultCode == RESULT_OK) {
				prevActivity = "UpdatedActivity";
				updatedCategory = (Category)data.getExtras().getSerializable("updatedCategory");
			}
		}
	}
	
	private class LoadCategoryTask extends AsyncTask<String, Void, String> {
		
		private final ProgressDialog progress = new ProgressDialog(MainActivity.this);
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress.setMessage("Loading...");
			progress.show();
		}
		
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			//---Load Category from database---
	        
	        //---Get location---
	        String str = "true";
	        try {
	        	if (gps.canGetLocation()) {
	        		loadCategoryFromDB();
					GPSLat = gps.getLat();
					GPSLng = gps.getLng();
					return str;
				} else {
					str = "false";
					return str;
				}
			} catch (Exception e) {
				// TODO: handle exception
				//showSettingAlert();
				str = "false";
				GPSLat = 10.767676;
				GPSLng = 106.76767;
				e.printStackTrace();
				return str;
			}
		}


		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
			//---Set adapter for list view category---
			if (progress.isShowing()) {
				progress.dismiss();
			}
			if (result == "true") {
				setAdapterForListCategory();	
			} else {
				showSettingAlert();
			}
		}
	}

	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		
	}
}
